<template>
  <div class="page-container page-footer-btn">
    <van-cell-group>
      <van-field v-model="form.warehouseName" label="仓库"  readonly />

      <van-field v-model="form.locationName"   :disabled="strings.isNotBlank(form.id) " label="库位" is-link clearable placeholder="请选择库位" @focus="open('Location')" />
      <van-field v-model="form.matrName" :disabled="strings.isNotBlank(form.id)" label="耗材" is-link clearable placeholder="请选择耗材" @focus="open('Matr')" />
      <van-field v-model="form.checkTypeName"   :disabled="strings.isNotBlank(form.id)" label="盘点类型" is-link clearable placeholder="请选择" @focus="open('checkType')" />

      <van-row >
        <van-col span="18"  >
          <FortenScan
            ref="scan"
            propPlaceholder="请扫描SN标签"
            propErrorMsg="请扫描正确的SN"
            :propTypeArr="['sn','rfid']"
            @scanCall="handleScanOver"
            :disabled="strings.isBlank(form.id) || form.flagFinished != 0"
          />
        </van-col>
        <van-col span="6" >
          <van-button size="small" type="primary" @click="RFIDScn" :disabled="strings.isBlank(form.id) || form.flagFinished != 0">扫描盘点</van-button>
        </van-col>
      </van-row>

    </van-cell-group>
    <van-row class="check-row">
      <van-col span="12"  ><h4>单号： {{strings.defaultString(form.busKey,'自动设置')}}</h4></van-col>
      <van-col span="12" style="    padding-top: 9px;" >
        <van-field       is-link clearable placeholder="选择盘点单" @focus="open('stockCheck')" />
      </van-col>
    </van-row>
    <van-row class="check-row">
      <van-col span="6" style="color: #1989fa">理论库存</van-col>
      <van-col span="6" style="color: green">正常</van-col>
      <van-col span="6" style="color: red">盘盈</van-col>
      <!--<van-col span="4" style="color: #ff8917">盘亏</van-col>-->
      <van-col span="6" style="color: #ff8917">盘亏/未盘</van-col>
    </van-row>
    <van-row class="check-row">
      <van-col span="6" style="color: #1989fa">{{form.stockNum}}</van-col>
      <van-col span="6" style="color: green">{{form.stockNormal}}</van-col>
      <van-col span="6" style="color: red">{{form.stockSurplus}}</van-col>
      <!--<van-col span="4" style="color: #ff8917">{{form.stockLoss}}</van-col>-->
      <van-col span="6" style="color: #ff8917">{{form.stockUnknown}}</van-col>
    </van-row>

    <van-tabs v-model="active" @change="activeChange">
      <van-tab title="盘盈/盘亏/未盘">
        <FortenList ref="listItem1" :propNoCheck="true"
                    :propAutoFetchData = 'false'
                    propUrl="/wm/stock_check_item/page"
                    @click="showStock"
        >
          <template  #default="{item,index}"  >
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">耗材:</van-col>
              <van-col span="21">{{item.matrName}}</van-col>
            </van-row>
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">品规:</van-col>
              <van-col span="21">{{item.matrSpec}}</van-col>
            </van-row>
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">RFID:</van-col>
              <van-col span="10"> {{item.rfid == null ? '无' :item.rfid}}</van-col>
              <van-col span="3">SN:</van-col>
              <van-col span="8">{{item.sn}}</van-col>
            </van-row>
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">库位:</van-col>
              <van-col span="15">{{item.locationName}}</van-col>
              <van-col span="3">状态:</van-col>
              <van-col span="3">{{getCheckStatus(item.checkStatus).value}}</van-col>
            </van-row>
          </template>
        </FortenList>
      </van-tab>
      <van-tab title="正常">
        <FortenList ref="listItem2" :propNoCheck="true"
                    :propAutoFetchData = 'false'
                    propUrl="/wm/stock_check_item/page"
                    @click="showStock"
        >
          <template  #default="{item, index}"  >
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">耗材:</van-col>
              <van-col span="21">{{item.matrName}}</van-col>
            </van-row>
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">品规:</van-col>
              <van-col span="21">{{item.matrSpec}}</van-col>
            </van-row>
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">RFID:</van-col>
              <van-col span="10"> {{item.rfid == null ? '无' :item.rfid}}</van-col>
              <van-col span="3">SN:</van-col>
              <van-col span="8">{{item.sn}}</van-col>
            </van-row>
            <van-row :style="{color: getCheckStatus(item.checkStatus).color}">
              <van-col span="3">库位:</van-col>
              <van-col span="15">{{item.locationName}}</van-col>
              <van-col span="3">状态:</van-col>
              <van-col span="3">{{getCheckStatus(item.checkStatus).value}}</van-col>
            </van-row>
          </template>
        </FortenList>
      </van-tab>
    </van-tabs>
    <van-action-sheet
      v-model="visible"  :actions="resultActions"
      get-container="body"  />
    <van-row type="flex" justify="space-around" class="footer-btn">
      <van-col span="8" >
        <van-button type="primary"    @click="handleBegin" :disabled="strings.isNotBlank(form.id)">开始盘点</van-button>
      </van-col>
      <van-col span="8" >
        <van-button type="danger"    @click="handleEnd" :disabled="strings.isBlank(form.id) || form.flagFinished != 0">结束盘点</van-button>
      </van-col>
    </van-row>


    <FortenList ref="listItemLocation" :propAutoFetchData = 'false'
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['name']"
                :propSearchTextAppend="'名称/代码'"
                propUrl="/base/location/pageForSelect"
                @change="changeLocation"
    >
      <template  #default="{item}"  >
        <van-row >
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="4">名称：</van-col>
          <van-col span="16">{{item.name}}</van-col>
        </van-row>
        <van-row  >
          <van-col span="4">
          </van-col>
          <van-col span="4">代码：</van-col>
          <van-col span="16">{{item.code}}</van-col>
        </van-row>
      </template>

    </FortenList>

    <FortenList ref="listItemMatr" :propAutoFetchData = 'false'
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['name','spec']"
                :propSearchTextAppend="'品名/品规'"
                propUrl="/base/matr/pageUsing"
                @change="changeMatr"
    >
      <template  #default="{item}"  >
        <van-row >
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="4">品名：</van-col>
          <van-col span="14">{{item.name}}</van-col>
        </van-row>
        <van-row  >
          <van-col span="4">
          </van-col>
          <van-col span="4">品规：</van-col>
          <van-col span="14">{{item.spec}}</van-col>
        </van-row>
      </template>
    </FortenList>


    <FortenList ref="listItemStockCheck" :propAutoFetchData = 'false'
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['name']"
                :propSearchTextAppend="'单号/库位/耗材'"
                propUrl="/wm/stock_check/page"
                @change="changeStockCheck"
    >
      <template  #default="{item}">
        <van-row >
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="4">仓库：</van-col>
          <van-col span="16">{{item.warehouseName}}</van-col>
        </van-row>
        <van-row  >
          <van-col span="4">库位：</van-col>
          <van-col span="20">{{item.locationName}}</van-col>
        </van-row>
        <van-row  >
          <van-col span="4">耗材：</van-col>
          <van-col span="8">{{item.matrName}}</van-col>
          <van-col span="4">单号：</van-col>
          <van-col span="8">{{item.busKey}}</van-col>
        </van-row>
        <van-row  >
          <van-col span="4">时间：</van-col>
          <van-col span="20">{{item.gmtCreate}}</van-col>
        </van-row>
      </template>

    </FortenList>


    <!-- 盘点类型选择-->
    <van-popup position="bottom" closeable v-model="selectVisible" >
      <van-radio-group  v-model="form.checkType" style="margin-top: 40px;">
        <van-cell-group>
          <van-cell @click="selectChange(item)" v-for="item in checkTypeList" :key="item.value" :title="item.label" clickable >
            <template #right-icon>
              <van-radio :name="item.value" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-popup>
  </div>
</template>
<script>
/* eslint-disable*/
import barcodeParse from '@/util/barcodeParse.js'
import {Dialog} from "vant"

export default {
  data() {
    return {
      scan: '',
      form: {},
      warehouseList: [],
      result: {
          matrName: '无',
          matrSpec: '无',
          locationName: '无',
          ready: '无',
          lost: '无' },
      visible: false,
      stocks: [],
      active: '1',
      showSheet: '',
      checkStatus: [
        {key: 0, value: '正常', color: 'green'},
        {key: 1, value: '盘盈', color: 'red'},
        {key: -1, value: '盘亏', color: '#ff8917'},
        {key: -9, value: '未盘', color: '#ff8917'},
       /* {key: -9, value: '未盘', color: 'gray'},*/
      ],
      selectVisible: false,
      checkTypeList: [
        {
          value: 'all',
          label: '所有库存',
          remark: '所选仓库库位耗材的所有库存',
          disabled: false
        },
        {
          value: 'today',
          label: '今天库存变动',
          remark: '所选仓库库位耗材今天的变动库存',
          disabled: false
        },
        {
          value: 'yesterday',
          label: '昨天库存变动',
          remark: '所选仓库库位耗材昨天的变动库存',
          disabled: false
        },
        {
          value: 'thisWeek',
          label: '本周库存变动',
          remark: '所选仓库库位耗材本周的变动库存',
          disabled: false
        },
        {
          value: 'thisMonth',
          label: '本月库存变动',
          remark: '所选仓库库位耗材本月的变动库存',
          disabled: false
        },
        {
          value: 'lastMonth',
          label: '上月库存变动',
          remark: '所选仓库库位耗材上月的变动库存',
          disabled: false
        }
      ]
    }
  },
  props: {
    propFlowKey: String
  },
  components: {
  },
  computed: {
    resultActions() {
      let actions = [
        {name: `品名： ${this.result.matrName}`},
        {name: `品规： ${this.result.matrSpec}`},
        {name: `库位： ${this.result.locationName}`},
        {name: `已盘： ${this.result.ready}`},
        {name: `未盘： ${this.result.lost}`},
      ]
      return actions
    }
  },
  methods: {
    RFIDScn(){
      //保存之后回调，只有有数据才会回调
      window.scanConfirm = (rfidList) => {
        this.utils.loadShow()
        let param= {
          ucList: rfidList,
          checkId: this.form.id,
        }
        this.$ajax.post('/wm/stock_check/RFIDScan', param).then(resp => {
          if (resp.code == 0) {
            if (resp.msg.indexOf('正常') != -1) {
              this.$notify.success(resp.msg)
            } else {
              this.$notify.warning(resp.msg)
            }
            this.$set(this.form, 'stockNum', resp.data.stockNum)
            this.$set(this.form, 'stockNormal', resp.data.stockNormal)
            this.$set(this.form, 'stockSurplus', resp.data.stockSurplus)
            this.$set(this.form, 'stockUnknown', resp.data.stockUnknown)
            this.$set(this.form, 'stockLoss', resp.data.stockLoss)
            this.reloadList()
            this.utils.loadHide()
          }
        })
      }
      this.utilPrint.openRfidScan()
    },
    //扫描
    async handleScanOver(scanValue) {
      this.utils.loadShow()
      this.$ajax.get(`/wm/stock_check/scan?uc=${scanValue}&checkId=${this.form.id}&isScan=1`).then(resp => {
        if (resp.code == 0) {
          if (resp.msg.indexOf('正常') != -1) {
            this.$notify.success(resp.msg)
          } else {
            this.$notify.warning(resp.msg)
          }
          this.$set(this.form, 'stockNum', resp.data.stockNum)
          this.$set(this.form, 'stockNormal', resp.data.stockNormal)
          this.$set(this.form, 'stockSurplus', resp.data.stockSurplus)
          this.$set(this.form, 'stockUnknown', resp.data.stockUnknown)
          this.$set(this.form, 'stockLoss', resp.data.stockLoss)
          this.reloadList()
          this.utils.loadHide()
        }
        this.utils.clearFocus(this,'scan','scan')
      })
    },

    //切换tab
    activeChange() {
     setTimeout(() => {
       this.reloadList()
     }, 500)
    },

    //刷新列表
    reloadList() {
      try {
        let wrapper1 = this.$newWrapper().eq('checkId', this.strings.defaultString(this.form.id,-1)).ne("checkStatus", '0')
        wrapper1.orderConditions.push({ field: 'gmtCreate', rule: 'desc' })
        this.$refs.listItem1.setQueryWrapper(wrapper1)
      }catch (e) {
      }
      try {
        let wrapper2 = this.$newWrapper().eq('checkId', this.strings.defaultString(this.form.id,-1)).eq("checkStatus", '0')
        wrapper2.orderConditions.push({ field: 'gmtCreate', rule: 'desc' })
        this.$refs.listItem2.setQueryWrapper(wrapper2)
      }catch (e) {
      }
    },

    //开始盘点
    handleBegin() {
      this.utils.loadShow()
      this.$ajax.post('/wm/stock_check/save', this.form).then(resp => {
        if (!this.form.id) {
          this.$set(this.form, 'id', resp.data.id)
          this.$set(this.form, 'stockNum', resp.data.stockNum)
          this.$set(this.form, 'stockNormal', resp.data.stockNormal)
          this.$set(this.form, 'stockSurplus', resp.data.stockSurplus)
          this.$set(this.form, 'stockUnknown', resp.data.stockUnknown)
          this.$set(this.form, 'busKey', resp.data.busKey)
          this.$set(this.form, 'stockLoss', resp.data.stockLoss)
          this.$set(this.form, 'flagFinished', 0)
          this.utils.loadHide()
          this.reloadList()
          this.$nextTick(() => {
            this.$refs.scan.focus()
          })
        }
      })
    },

    //结束盘点
    handleEnd() {
      this.$dialog.confirm({
        message: '是否结束当前盘点?',
      }).then(() => {
        this.utils.loadShow()
        this.form.flagFinished = 1
        let checkItem = {
          id: this.form.id,
          warehouseId: this.form.warehouseId,
          flagFinished: this.form.flagFinished
        }
        this.$ajax.post('/wm/stock_check/save', checkItem).then(response => {
          this.reload()
          this.utils.loadHide()
        })
      }).catch(() => {
        // on cancel
      })
    },

    //盘点类型选择后
    selectChange(item) {
      this.selectVisible = false
      this.form.checkType = item.value
      this.form.checkTypeName = item.label
    },

    //盘点类型显示名称
    setCheckType(){
      let findIndex = this.checkTypeList.findIndex(ob => ob.value == this.form.checkType)
      if (findIndex != -1) {
        this.form.checkTypeName = this.checkTypeList[findIndex].label
      }
    },

    //打开弹框
    open(type) {
      if (type == 'Location') {
        let wrapper = this.$newWrapper().eq('warehouseId', this.form.warehouseId).ne('name', this.form.warehouseName)
        this.$refs.listItemLocation.setQueryWrapper(wrapper)
        this.$refs.listItemLocation.show()
      } else  if (type == 'Matr'){
        //包含库位时，则筛选库位耗材范围设置
        if (this.strings.isNotBlank(this.form.locationId)) {
          this.$refs.listItemMatr.setUserParam({sqlFilter:" and id in (select matr_id from location_limit_matr where location_id='"+this.form.locationId+"') "})
        } else {
          this.$refs.listItemMatr.setUserParam({})
        }
        this.$refs.listItemMatr.show()
      }  else  if (type == 'checkType'){ //盘点类型
        this.selectVisible = true
      } else {
        let wrapper = this.$newWrapper().ne('flagFinished', 1).eq('warehouseId', this.form.warehouseId)
        wrapper.orderConditions.push({ field: 'gmtCreate', rule: 'desc' })
        this.$refs.listItemStockCheck.setQueryWrapper(wrapper)
        this.$refs.listItemStockCheck.show()
      }
    },

    //库位选择
    changeLocation(item) {
      this.$set(this.form, 'locationId', item.id)
      this.$set(this.form, 'locationName', item.name)
    },

    //耗材选择
    changeMatr(item) {
      this.$set(this.form, 'matrId', item.id)
      this.$set(this.form, 'matrName', item.name)
    },

    //盘点单选择
    changeStockCheck(item) {
      this.$set(this.form, 'id', item.id)
      this.$set(this.form, 'stockNum', item.stockNum)
      this.$set(this.form, 'stockNormal', item.stockNormal)
      this.$set(this.form, 'stockSurplus', item.stockSurplus)
      this.$set(this.form, 'stockUnknown', item.stockUnknown)
      this.$set(this.form, 'busKey', item.busKey)
      this.$set(this.form, 'stockLoss', item.stockLoss)
      this.$set(this.form, 'flagFinished', 0)
      this.$set(this.form, 'checkType', item.checkType)
      this.reloadList()
      this.utils.clearFocus(this,'scan','scan')
      this.setCheckType()
    },

    //刷新选择
    reload(isByTop) {
      if (isByTop != true && this.form.flagFinished == 0) {
        this.$dialog.alert({
          title: '标题',
          message: '当前盘点任务尚未结束，请先结束!',
        }).then(() => {

        }).catch(() => {
        })
        return
      }
      this.form = {}
      this.form.stockNum = 0
      this.form.stockSurplus = 0
      this.form.stockUnknown = 0
      this.form.stockLoss = 0
      this.stocks = []
      this.form.warehouseId = this.utils.getCurrentWarehouse().warehouseId
      this.form.warehouseName = this.utils.getCurrentWarehouse().warehouseName
      this.reloadList()
      if (this.strings.isBlank(this.form.warehouseId)) {
        Dialog.alert({
          title: '系统提示',
          message: '请先到工作台设置当前仓库，再进行操作',
        })
          .then(() => {
            this.$store.commit('SET_WORKBENCH_ROUTE', { name: 'dashboard' })
          })
      }
    },
    getCheckStatus(checkStatus) {
      return this.checkStatus.filter(ob => ob.key ==checkStatus)[0]
    },
    showStock(item) {
      this.utils.loadShow()
      let params = {
        matrId: item.matrId,
        locationId: item.locationId,
        checkId: item.checkId
      }
      this.$ajax.get('/wm/stock_check_item/getStockSumByMatr', {params}).then(response =>{
        this.utils.loadHide()
        if(response.code == 0){
          this.result = response.data
          this.visible = true
        } else {
          this.$notify.warning(response.msg)
        }
      }).catch(err =>{
        this.utils.loadHide()
      })
    },
  },
  mounted() {
    this.reload()
  }
}
</script>

<style lang="scss" scoped>
  .van-col {
    text-align: center;
  }
  .popup {
    width: 60%;
    height: 100%;
  }
  .check-row {
    font-size: 18px;
    margin: 5px;
    .red {
      color: red
    }
    .green {
      color: green
    }
    .gray {
      color: gray
    }
    .showRow {
      height: 20%;
      font-size: 18px;
    }
  }
</style>
